package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class OperationLogAspect {
    private static final Logger log = LoggerFactory.getLogger(OperationLogAspect.class);
    @Autowired
    private OperateLogMapper operateLogMapper;
    // 环绕通知
    @Around("@annotation(com.itheima.aop.annotation.LogOperation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        log.info("记录操作日志开始");
        //创建一个日志对象用于保存日志信息
        OperateLog operateLog = new OperateLog();
        //给实体类赋值当前的系统时间
        operateLog.setOperateTime(LocalDateTime.now());
        //Threadlocal，TokenFilter校验时，解析得登录用户id，存入ThreadLocal
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        //给实体类赋值方法参数
        //获取方法参数
        Object[] args = joinPoint.getArgs();
        operateLog.setMethodParams(args[0].toString());
        //给实体类赋值方法名
        operateLog.setMethodName(joinPoint.getSignature().getName());
        //给实体类赋值类名
        operateLog.setClassName(joinPoint.getSignature().getDeclaringTypeName());

        // 执行方法
        Object result = null;
        try {
            result = joinPoint.proceed();
            operateLog.setReturnValue(result.toString());
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            //TODO 保存日志信息到数据库中
            //记录方法的耗时
            operateLog.setCostTime(System.currentTimeMillis() - startTime);
            operateLogMapper.insert(operateLog);
            //移除存入的数据
        }
        log.info("记录操作日志结束");
        return result;
    }
}
